package kotlinx.coroutines.script.tes

import kotlinx.coroutines.Dispatchers
import v9.assist.captureScreenshot
import java.io.File

object CrashUtils {
    private val crashLogDir get() = FileUtils.externalCacheDir("crash")
    val crashText: File? get() {
        val childList = crashLogDir.listFiles()
        if (childList.isNullOrEmpty()) return null
        return childList[0]
    }

    private val errorImageForStopped get() = File(FileUtils.externalCacheDir("errorImageStopped"), "error.jpg")
    private val errorImageDir get() = FileUtils.externalCacheDir("errorImage")

    fun saveErrorStoppedScreenshotToDisk() {
        appScopeLaunch(Dispatchers.IO) {
            // 将截图保存到本地
//            Screenshot.get().ss?.let {
            captureScreenshot()?.let {
                try {
                    errorImageForStopped.delete()
                } catch (ignore: Throwable) {}

                val image = errorImageForStopped
                FileUtils.writeBitmapToDisk(image, it, quality = 30)
                printLog { "CrashUtils save image ${ System.currentTimeMillis().toTime("yyyy/MM/dd HH:mm:ss")}" }
            }
        }
    }



    fun deleteAllScreenshot() {
        errorImageDir.listFiles()?.forEach {
            try {
                val deleted = it?.delete()
                printLog { "删除文件 ${it.name} ${if (deleted == true) "成功" else "失败" }" }
            } catch (e: Throwable) {
                e.printStackTrace()
            }
        }
    }

    fun getScreenshotListByDisk(): List<File> {
        return errorImageDir.listFiles()
            ?.filter { it.name.startsWith("error") }
            ?.sortedByDescending { it.name.replace(".jpg", "").replace("error", "").toLong() } ?: listOf()
    }
    fun getScreenshotErrorStoppedByDisk(): File {
        return errorImageForStopped
    }
//    fun getScreenshotUnknown150ByDisk(): File {
//        return unknown150
//    }

//    private var lastSentTimestamp: Long? = null
//    private val lastSentTs: Long get() {
//        return lastSentTimestamp ?: (readByDisk("lastSentTimestamp")?.toLongOrNull() ?: 0).also { lastSentTimestamp = it }
//    }
//    private fun updateLastSentTimestamp(value: Long) {
//        lastSentTimestamp = value
//        writeToDisk("lastSentTimestamp", value.toString())
//    }
//    val ac: String get () {
//        val encryptedStr = "EHhiPllWwwoFxALDWsWHRgwpSnJR7+plrW1ArVxeduF7JZ3+9LIgxLbyguHgDhcFrUOhlNrBoVdm\n" +
//                "T1Q2rFaJsdr/l1zHfgIfK1v7FARHi5z0HsZODT8Lg0fEoulWfv1gR7tI4qjCOe89Eja26YIcniwQ\n" +
//                "O6vNGGg2xShbbu58ob8JdOzt7Omqjqj7lByxJ+P47DQLXzyPwwtvqWLSgOdFm7EUqsixK33H7/jH\n" +
//                "YBJSh6iZTMf1PdgiUyBkxX0tVZ2a+t4ek0sCIM4om2OmPwtdaN/oW6WOX2IA8J6kPBFfmEtWoGTO\n" +
//                "zS7o9jHnbbeQzaLACVROCvvyApRawZ9oBa/hyA=="
//        val decryptBytes: ByteArray? = try {
//            RSAUtils.decryptByPublicKeyForSpilt(
//                Base64Decoder.decodeToBytes(encryptedStr),
//                Keys.publicKey.encoded
//            )
//        } catch (e: Throwable) {
//            e.printStackTrace()
//            null
//        }
//        return String(decryptBytes!!)
//    }
//    fun sentMailAlert() {
//        if (System.currentTimeMillis() - lastSentTs > 600000) {
//            val receivedAddress = Properties.receivedEmail
//            if (receivedAddress.isNotEmpty()) {
//                val from = AESUtils.decrypt("immortal", "pQE78UR/+4qRnhPyfAIuruqloB66XRMv9su2fPUZjrI=")  // "fio517309507@foxmail.com"
//                val mail = Mail().apply {
//                    mailServerHost = "smtp.qq.com"
//                    mailServerPort = "587"
//                    fromAddress = from
//                    password = ac // "dywruewxcyfjcbcf"
//                    toAddress = arrayListOf(receivedAddress)
//                    subject = "运行异常提示"
//                    content = "你开启的任务在${System.currentTimeMillis().toTime("yyyy/MM/dd HH:mm:ss")}异常终止，已运行${OutputView.runTime}秒"
//                }
//                MailSender.getInstance().sendMail(mail)
//                updateLastSentTimestamp(System.currentTimeMillis())
//                printLog { "sentMailAlert success" }
//            } else printLog { "sentMailAlert no toAddress" }
//        } else printLog { "sentMailAlert too frequently" }
//    }
}